#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qfiledialog.h"
#include "qmessagebox.h"
#include "qdebug.h"
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <fileapi.h>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    mCurDir = QString("D:/");
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_dateTimeEdit_dateTimeChanged(const QDateTime &dateTime)
{
 qDebug() <<dateTime.date();
}


HANDLE MainWindow::getFileHandle(QString fileName){
    HANDLE hFile;
    DWORD dwRet;
    const wchar_t* wstr = reinterpret_cast<const wchar_t *>(fileName.utf16());
//    hFile = ::CreateFile(wstr,               // file to open
//                          GENERIC_READ,          // open for reading
//                          FILE_SHARE_READ,       // share for reading
//                          NULL,                  // default security
//                          OPEN_EXISTING,         // existing file only
//                          FILE_ATTRIBUTE_NORMAL, // normal file
//                          NULL);                 // no attr. template
    //getthe handle to the file
    hFile = CreateFile(wstr, FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
       if( hFile == INVALID_HANDLE_VALUE)
       {
           printf("Could not open file (error %d\n)", GetLastError());
           return NULL;
       }
//       HANDLE hFileMap = ::CreateFileMapping(hFile,
//               NULL,
//               PAGE_READWRITE,
//               NULL,
//               NULL,
//               L"Resource");
//       dwRet = GetFinalPathNameByHandle( hFile, Path, BUFSIZE, VOLUME_NAME_NT );
//       if(dwRet < BUFSIZE)
//       {
//           _tprintf(TEXT("\nThe final path is: %s\n"), Path);
//       }
//       else printf("\nThe required buffer size is %d.\n", dwRet);

       return hFile;
}

void MainWindow::on_pushButton_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(
            this,
            tr("open a file."),
            mCurDir,
            tr("images(*.png *jpeg *bmp);;video files(*.avi *.mp4 *.wmv);;All files(*.*)"));
        if (fileName.isEmpty()) {
            QMessageBox::warning(this, "Warning!", "Failed to open the video!");
        }
        else {
            ui->plainTextEdit->setPlainText(fileName);
        }

            if (!fileName.isEmpty())
               {
                   QString infoList;

                   QFile file(fileName);

                   if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
                   {
                       infoList += tr("Can not open file: %1 \n").arg(fileName);
                   }
                   else
                   {
                       infoList += tr("Open file: %1 Successfully\n").arg(fileName);
                   }

                   QFileInfo info(fileName);
                   mCurDir = info.absolutePath();

                   if (info.exists())
                   {

                       infoList += tr("文件名称: %1 \n").arg(info.fileName());
                       infoList += tr("文件大小: %1 Bytes\n").arg(info.size());
                       infoList += tr("创建时间: %1 \n").arg(info.created().toString("yyyy-MM-dd hh:mm:ss"));
                       infoList += tr("修改时间: %1 \n").arg(info.lastModified().toString("yyyy-MM-dd hh:mm:ss"));
                       infoList += tr("读取时间: %1 \n").arg(info.lastRead().toString("yyyy-MM-dd hh:mm:ss"));

                       ui->label->setText(infoList);
                   }
               }

}

// Convert a QDateTime to a FILETIME.
FILETIME MainWindow::toWinFileTime(const QDateTime &dateTime)
{
    // Definition of FILETIME from MSDN:
    // Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).
    QDateTime origin(QDate(1601, 1, 1), QTime(0, 0, 0, 0), Qt::UTC);
    // Get offset - note we need 100-nanosecond intervals, hence we multiply by
    // 10000.
    qint64 _100nanosecs = 10000 * origin.msecsTo(dateTime);
    // Pack _100nanosecs into the structure.
    FILETIME fileTime;
    fileTime.dwLowDateTime = _100nanosecs;
    fileTime.dwHighDateTime = (_100nanosecs >> 32);

    return fileTime;
}
void MainWindow::on_pushButton_2_clicked()
{

      QString fileName =  ui->plainTextEdit->toPlainText();
      QDateTime datetime = ui->dateTimeEdit->dateTime().toUTC();  // 日期时间

      quint16 year = datetime.date().year();             //年
      quint8 month = datetime.date().month();			   //月
      quint8 day = datetime.date().day();				   //日
      quint8 hour = datetime.time().hour();			   //时
      quint8 minute = datetime.time().minute();          //分
      quint8 second = datetime.time().second();

      HANDLE hFile = getFileHandle(fileName);

      SYSTEMTIME createTime;
      ::GetSystemTime(&createTime);
     createTime.wDay = day;            //changes the day
     createTime.wMonth = month;         //changes the month
     createTime.wYear = year;        //changes the year
     createTime.wHour = hour;           //changes the hour
     createTime.wMinute = minute;         //changes the minute
     createTime.wSecond = second;         //changes the second



     SYSTEMTIME lastWriteTime;
     ::GetSystemTime(&lastWriteTime);
     lastWriteTime.wDay = day;        //changes the day
     lastWriteTime.wMonth = month;      //changes the month
     lastWriteTime.wYear = year;     //changes the year
     lastWriteTime.wHour = hour;        //changes the hour
     lastWriteTime.wMinute = minute;     //changes the minute
     lastWriteTime.wSecond = second;     //changes the second


     SYSTEMTIME lastAccessTime;
     ::GetSystemTime(&lastAccessTime);
//         lastAccessTime.wDay = 20;       //changes the day
//         lastAccessTime.wMonth = 07;     //changes the month
//         lastAccessTime.wYear = 2017;    //changes the year
//         lastAccessTime.wHour = 15;      //changes the hour
//         lastAccessTime.wMinute = 31;    //changes the minute
//         lastAccessTime.wSecond = 8;     //changes the second

         //creation of a filetimestruct and convert our new systemtime
         FILETIME lastWriteFiletime;
         ::SystemTimeToFileTime(&lastWriteTime, &lastWriteFiletime);

         FILETIME createFiletime;
         ::SystemTimeToFileTime(&createTime, &createFiletime);

         FILETIME lastAccessFileTime;
         ::SystemTimeToFileTime(&lastAccessTime, &lastAccessFileTime);

         //set the filetime on the file
         ::SetFileTime(hFile, ui->createCheckBox->isChecked() ? &createFiletime : NULL, &lastAccessFileTime,  ui->modifyCheckBox->isChecked() ? &lastWriteFiletime: NULL);


        ::CloseHandle(hFile);

        if (!fileName.isEmpty())
         {
             QString infoList;

             QFile file(fileName);
             if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
             {
                 infoList += tr("Can not open file: %1 \n").arg(fileName);
             }
             else
             {
                 infoList += tr("Open file: %1 Successfully\n").arg(fileName);
             }

             QFileInfo info(fileName);
             if (info.exists())
             {

                 infoList += tr("文件名称: %1 \n").arg(info.fileName());
                 infoList += tr("文件大小: %1 Bytes\n").arg(info.size());
                 infoList += tr("创建时间: %1 \n").arg(info.created().toString("yyyy-MM-dd hh:mm:ss"));
                 infoList += tr("修改时间: %1 \n").arg(info.lastModified().toString("yyyy-MM-dd hh:mm:ss"));
                 infoList += tr("读取时间: %1 \n").arg(info.lastRead().toString("yyyy-MM-dd hh:mm:ss"));

                 ui->label->setText(infoList);
             }
         }

}
